package cloudspace.ui;

import org.apache.log4j.Logger;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.util.Clients;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.impl.LabelElement;


public class InlineEditor
{
    private InlineEditor()
    {
        // Prevent instantiation.
    }


    @SuppressWarnings("unchecked")
    public static <T extends LabelElement> void attachToElement(
        final T element,
        final InlineEditListener listener )
    {
        T newCell = null;

        try
        {
            newCell = (T)element.getClass().newInstance();
        }
        catch ( Exception e )
        {
            log.error( "Could not instantiate the class "
                + element.getClass().getCanonicalName(), e );
            return;
        }

        final T editableCell = newCell;
        element.getParent().insertBefore( editableCell, element );
        element.detach();

        final Textbox textbox = new Textbox();
        textbox.setValue( element.getLabel() );
        textbox.setStyle( "margin: 0" );
        editableCell.appendChild( textbox );

        textbox.addEventListener( "onCancel", new EventListener()
        {
            public void onEvent( Event event ) throws Exception
            {
                editableCell.getParent().insertBefore( element, editableCell );
                editableCell.detach();

                listener.decline();
                listener.finish();
            }
        } );

        EventListener okListener = new EventListener()
        {
            public void onEvent( Event event ) throws Exception
            {
                editableCell.getParent().insertBefore( element, editableCell );
                editableCell.detach();

                if ( textbox.getText().length() > 0 )
                {
                    element.setLabel( textbox.getText() );
                    listener.accept( textbox.getText() );
                }
                else
                {
                    listener.decline();
                }

                listener.finish();
            }
        };

        textbox.addEventListener( "onOK", okListener );
        textbox.addEventListener( "onBlur", okListener );

        Clients.scrollIntoView( editableCell );
        textbox.focus();
    }

    private static final Logger log = Logger.getLogger( InlineEditor.class );
}
